/**
 * 
 */
package com.edu.base.common;

import java.util.Random;

import org.springframework.stereotype.Component;

import com.edu.base.common.utils.Encodes;

/**
 * 系统管理，安全相关实体的管理类,包括用户、角色、菜单.
 * @author
 * @version 2013-12-05
 */
@Component
public class SystemService  {
	
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	public static final int SALT_SIZE = 8;
	
	 //生成numb位随机数字
    public static final char[] CHARS={'0','1','2','3','4','5','6','7','8','9'};
    public static Random random=new Random();
 
	/**
	 * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
	 */
	public static String entryptPassword(String plainPassword) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
	}
	
	/**
	 * 验证密码
	 * @param plainPassword 明文密码
	 * @param password 密文密码
	 * @return 验证成功返回true
	 * @throws Exception 
	 */
	public static boolean validatePassword(String plainPassword, String password) throws Exception {
		try {
			byte[] salt = Encodes.decodeHex(password.substring(0,16));
			byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
			return password.equals(Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword));
		} catch (Exception e) {
 			 throw  new  Exception("验证密码错误");
		}
	}
	

    public static String getRandomString(int numb){
        StringBuffer buffer=new StringBuffer();
        for(int i=0;i<numb;i++){
            buffer.append(CHARS[random.nextInt(CHARS.length)]);
        }
        return buffer.toString();
    }

	public static void main(String[] args) throws Exception {
		System.out.println(validatePassword("123456", "0b10f600230dbf04619fae8d3c0bd99e"));
		System.out.println(validatePassword("123465", "2f20a0848749f275b04c093a527469aa"));
	}

	
}
